﻿using System;
using System.Text;
using System.Globalization;

namespace Utilities
{
    public static class JsonConverter
    {
        public static string Convert(object o)
        {
            if (o == null)
            {
                return "null";
            }

            Type type = o.GetType();
            string value = o.ToString();

            if (type == typeof(string))
            {
                return Convert(value);
            }

            if (type == typeof(bool))
            {
                return value.ToLowerInvariant();
            }

            if (type.IsEnum)
            {
                int val = (int)o;
                return val.ToString();
            }

            // TODO: Convert dates

            return value;
        }

        public static string Convert(string s)
        {
            if (s == null)
            {
                return "null";
            }

            StringBuilder sb = new StringBuilder();
            sb.Append('"');

            foreach (char c in s.ToCharArray())
            {
                switch (c)
                {
                    case '\\':
                    case '"':
                        {
                            sb.Append('\\');
                            sb.Append(c);
                        }
                        break;
                    case '\b': sb.Append("\\b"); break;
                    case '\t': sb.Append("\\t"); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\f': sb.Append("\\f"); break;
                    case '\r': sb.Append("\\r"); break;
                    
                    default:
                        {
                            if (c < ' ')
                            {
                                sb.Append("\\u");
                                sb.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
                            }
                            else
                            {
                                sb.Append(c);
                            }
                        }
                        break;
                }
            }

            sb.Append('"');

            return sb.ToString();
        }
    }
}
